package com.leap.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.StorageClass;
import com.leap.entity.dto.MediaUploadDTO;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.info.MultimediaInfo;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

public class UploadUtil {
    //阿里域名
    private static final String ALI_DOMAIN = "https://knowlab.xyz/";

    public static String ImgUpload(MultipartFile file) throws IOException {

        //生成文件名字
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        //地域节点
        String endpoint = "http://oss-cn-hongkong.aliyuncs.com";
        String accessKeyId = "LTAI5tCMv3R1icoaGUwNMf2Q";
        String accessKeySecret = "VFjB4IF1dIbgJLGN6NgNuSn18Rq8bI";
        //OSS客户端对象
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpeg");
        ossClient.putObject(
                "knwolab02",
                fileName,
                file.getInputStream(),
                objectMetadata
        );
        ossClient.shutdown();
        return ALI_DOMAIN + fileName;
    }

    public static MediaUploadDTO VideoUpload(MultipartFile file) throws IOException, EncoderException {

        //生成文件名字
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        //地域节点
        String endpoint = "http://oss-cn-hongkong.aliyuncs.com";
        String accessKeyId = "LTAI5tCMv3R1icoaGUwNMf2Q";
        String accessKeySecret = "VFjB4IF1dIbgJLGN6NgNuSn18Rq8bI";
        //OSS客户端对象
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("video/mp4");
        ossClient.putObject(
                "knwolab02",
                fileName,
                file.getInputStream(),
                objectMetadata
        );
        ossClient.shutdown();

        URL videoUrl = new URL(ALI_DOMAIN + fileName);
        MultimediaObject multimediaObject = new MultimediaObject(videoUrl);
        MultimediaInfo info = multimediaObject.getInfo();
        long duration = info.getDuration();
        long seconds = duration / 1000;
        return MediaUploadDTO.builder()
                .fileUrl(ALI_DOMAIN + fileName)
                .duration(seconds)
                .build();
    }


}
